import 'dart:async';

import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

import 'room_music_center_controller.dart';

/// 收藏的音乐列表
class RoomMusicCollectController extends GetxController {
  late RoomMusicCenterController centerController;

  final MusicChartInfo chartInfo;
  RoomMusicCollectController(this.chartInfo);
  RefreshController controller = RefreshController(initialRefresh: false);
  bool hasLoading = false;
  List<CollectedMusic> get data => centerController.collectedMusics;
  int get count => data.length;
  StreamSubscription? subscription;

  @override
  void onInit() {
    super.onInit();
    centerController = Get.find<RoomMusicCenterController>();
    subscription = centerController.subscribeCollectedMusic.listen((v) {
      update();
    }, onError: (value) {
      update();
    });
  }

  @override
  void onReady() {
    super.onReady();
    loadData();
  }

  @override
  void onClose() {
    subscription?.cancel();
    super.onClose();
  }

  Future<void> loadData() async {
    // var result = await RtcApi.instance.getCollectList();
    // if (result.isSuccess && result.data != null) {
    //   List<CollectedMusic> data = [];
    //   for (var element in result.data!.contentList) {
    //     Map<String, dynamic> responseData = jsonDecode(element.contentStr);
    //     var song = CollectedMusic.fromJson(element.id.toInt(),responseData);
    //     data!.add(song);
    //   }
    //   centerController.updateCollectStatus(data!);
    //   hasLoading = true;
    // }
    controller.refreshCompleted();
    update();
  }

  void playAll() async {
    if (count > 0) {
      List<Music> list = data.map<Music>((e) => e.music).toList();
      centerController.playlist = list;
      Music first = list.first;
      MediaPlayerState state = await centerController.playState(first);
      if (state != MediaPlayerState.playerStatePlaying) {
        centerController.play(list.first);
      }
    }
  }
}
